import { Reducer, Effect, Subscription } from 'umi';
import { 
    fetchQuestionsType,
    fetchSubject,
    fetchExamType
} from './service'


export interface StateType {
  questionsType: Array<any>;
  subject: Array<any>;
  examType: Array<any>;
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetchQuestionInitData: Effect;
  };
  subscriptions: {
      initData: Subscription
  },
  reducers: {
    changeState: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'question',

  state: {
    questionsType: [],
    subject: [],
    examType: []

  },

  subscriptions: {
    initData ({ dispatch }) {
        dispatch({
            type: 'fetchQuestionInitData'
        })
    }
  },

  effects: {
    *fetchQuestionInitData ({payload}, { call, put }) {
      const initData = () => Promise.all([
        fetchQuestionsType(),
        fetchSubject(),
        fetchExamType()
      ])
      const res = yield call(initData)
      yield put({
        type: 'changeState',
        payload: {
            questionsType: res[0].data,
            subject: res[1].data,
            examType: res[2].data
        }
      })
      console.log(res)
    }
  },

  reducers: {
    changeState(state, { payload }) {
      return {
        ...state,
        ...payload
      };
    },
  },
};

export default Model;
